<template>
  <div class="app-container" v-loading="loading">
    <el-form
      ref="formRef"
      :inline="false"
      :model="form"
      :rules="rules"
      label-width="110px"
      :disabled="parentHandleType == 'view'"
    >
      <!-- <el-form-item label="来源" prop="source">
        <el-radio-group v-model="form.source" :disabled="!!form.id">
          <el-radio
            v-for="dict in order_source"
            :key="dict.value"
            :value="dict.value"
            >{{ dict.label }}</el-radio
          >
        </el-radio-group>
      </el-form-item> -->
      <el-form-item label="选择订单" prop="orderList">
        <el-button type="primary" @click="handleOrderList" :disabled="!!form.id"
          >选择生产订单</el-button
        >
        <el-table
          :data="form.orderList"
          border
          style="width: 100%; margin-top: 10px"
        >
          <el-table-column label="订单编号" prop="orderCode" />
          <el-table-column label="产品编码" prop="prodCode" />
          <el-table-column label="产品名称" prop="prodName" />
          <el-table-column label="计划产量" prop="planNumber" />
          <el-table-column label="单位" prop="unit" />
          <el-table-column label="计划开始时间" prop="planStartTime">
            <template #default="scope">
              <span>{{ scope.row.planStartTime }}</span>
            </template>
          </el-table-column>
          <el-table-column label="计划结束时间" prop="planEndTime">
            <template #default="scope">
              <span>{{ scope.row.planEndTime }}</span>
            </template>
          </el-table-column>
          <el-table-column label="工厂" prop="factoryName" />
          <el-table-column label="工段" prop="workShopName" />
          <el-table-column label="来源" prop="source"
            ><template #default="scope">
              <dict-tag :options="order_source" :value="scope.row.source" />
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="form.remark"
          type="textarea"
          placeholder="请输入内容"
          style="width: 625px"
        ></el-input>
      </el-form-item>
    </el-form>
    <div class="wordOrderDiv">
      <div>生产工单</div>
      <div>
        <el-button
          link
          v-if="parentHandleType != 'view'"
          type="primary"
          @click="handleBatchSettings()"
          :disabled="!!form.id"
          >批量设置</el-button
        >
        <el-button
          link
          type="primary"
          v-if="parentHandleType != 'view'"
          @click="handleAddWorkOrder()"
          :disabled="!!form.id"
          >增加工单</el-button
        >
        <el-button
          link
          v-if="form.source == 'ERP' && parentHandleType != 'view'"
          type="primary"
          @click="handleDisOrder()"
          >已拆解工单</el-button
        >
      </div>
    </div>
    <div
      style="width: 100%; height: 1px; background-color: #eee; margin: 10px 0"
    ></div>
    <el-table
      :data="workOrderList"
      border
      :header-cell-class-name="start"
      style="width: 100%; margin-top: 10px"
    >
      <el-table-column label="工单编号" prop="workOrderCode">
        <template #default="scope">
          <code-input
            v-model="scope.row.workOrderCode"
            code="PLAN_CODE"
            :disabled="!!scope.row.id"
            placeholder="请输入工单编号"
          />
        </template>
      </el-table-column>
      <el-table-column label="产线" prop="lineCode">
        <template #default="scope">
          <el-input
            v-model="scope.row.lineName"
            clearable
            v-if="!!scope.row.id"
            disabled
          />
          <el-select
            v-model="scope.row.lineCode"
            placeholder="请选择产线"
            clearable
            filterable
            @change="handleSearchProdChange(scope.row.lineCode, scope.$index)"
            v-else
          >
            <el-option
              v-for="(item, index) in workshopOptions"
              :key="index"
              :label="item.name"
              :value="item.code"
            >
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="工艺段" prop="sectionCode">
        <template #default="scope">
          <el-input
            v-model="scope.row.sectionName"
            clearable
            v-if="!!scope.row.id"
            disabled
          />
          <el-select
            v-model="scope.row.sectionCode"
            placeholder="请选择工艺段"
            clearable
            filterable
            :disabled="!!scope.row.id"
            @change="
              handleSearchSectionChange(scope.row.sectionCode, scope.$index)
            "
            v-else
          >
            <el-option
              v-for="(item, index) in scope.row.sectionList"
              :key="index"
              :label="item.name"
              :value="item.code"
            >
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="计划产量" prop="planNumber">
        <template #default="scope">
          <!-- <el-input
            v-model="scope.row.planNumber"
            placeholder="请输入计划产量"
            clearable
            :disabled="parentHandleType == 'view'"
          /> -->
          <el-input-number
            v-model="scope.row.planNumber"
            controls-position="right"
            :min="0"
            :max="99999.0"
            :precision="2"
            :disabled="parentHandleType == 'view'"
          ></el-input-number>
        </template>
      </el-table-column>
      <el-table-column label="单位" label-class-name='noShowStar'  width="60" />
      <el-table-column label="计划时间" prop="planTime" width="300">
        <template #default="scope">
          <el-date-picker
            v-model="scope.row.planTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            style="width: 260px"
            :disabled="parentHandleType == 'view'"
          ></el-date-picker>
          <!-- <el-date-picker
            v-model="scope.row.planStartTime"  
            type="date"
            value-format="YYYY-MM-DD"
            style="width: 150px"
            :disabled="!!scope.row.id"
          ></el-date-picker> -->
        </template>
      </el-table-column>
      <!-- <el-table-column label="计划结束时间" prop="planEndTime" width="180">
        <template #default="scope">
          <el-date-picker
            v-model="scope.row.planEndTime"
            type="date"
            value-format="YYYY-MM-DD"
            style="width: 150px"
            :disabled="!!scope.row.id"
          ></el-date-picker>
        </template>
      </el-table-column> -->
      <el-table-column
        label="操作"
        width="100"
        label-class-name='noShowStar'
        v-if="parentHandleType != 'view'"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleDel(scope.row)"
            :disabled="!!scope.row.id"
            >移除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <orderList
      @changeList="changeList"
      :title="'选择生产订单'"
      :openOrder="openOrder"
    ></orderList>
    <workOrderBatchSet
      @changeWorderOrderBatchList="changeWorderOrderBatchList"
      :title="'工单批量设置'"
      :openWorderOrderBatch="openWorderOrderBatch"
      :orderList="form.orderList"
    ></workOrderBatchSet>
    <disOrderList
      @changeDisOrderList="changeDisOrderList"
      :title="'已拆解工单'"
      :openDisOrder="openDisOrder"
      :orderList="form.orderList"
    ></disOrderList>
  </div>
</template>

<script setup name="Data">
import { getMatCodeList } from "@/api/technology/processRoute";
import { getFactoryTree, depeIdSelectList } from "@/api/system/dept";
import {
  listWorkOrder,
  getOrderList,
  getWorkOrder,
  delWorkOrder,
  addWorkOrder,
  updateWorkOrder,
} from "@/api/base/workOrder/workOrder";
import orderList from "./orderList";
import disOrderList from "./disOrderList";
import workOrderBatchSet from "./workOrderBatchSet";
import { nextTick, reactive, useAttrs } from "vue";
const { proxy } = getCurrentInstance();
const { order_source } = proxy.useDict("order_source");

const attrs = useAttrs();
const start = ({ row, rowIndex, column, columnIndex }) => {
  if (columnIndex != 7) {
    return "start";
  }
};

const data = reactive({
  rules: {
    source: [{ required: true, message: "来源不能为空", trigger: "change" }],
    orderList: [
      {
        required: true,
        type: "array",
        message: "选择订单不能为空",
        trigger: "change",
      },
    ],
  },
  form: {
    // ERP
    source: "",
    orderList: [],
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userName: undefined,
  },
});
const parentHandleType = ref("add");
const workOrderList = ref([]);
const openOrder = ref(false);
const loading = ref(false);
const openDisOrder = ref(false);
const openWorderOrderBatch = ref(false);
const formRef = ref(null);
const { form, rules } = toRefs(data);
const workshopOptions = ref([]);
const emit = defineEmits(["close", "setTitle", "setActions", "setIsActionTop"]);
const actions = ref([
  {
    text: "取 消",
    theme: "",
    handle: () => {
      cancel();
    },
  },
  {
    text: "确 定",
    theme: "primary",
    handle: () => {
      submitForm();
    },
    loading: false,
  },
]);

function getDetail(id) {
  loading.value = true;
  reset();
  getOrderList({ orderCode: id }).then((res) => {
    // form.value = res.data;
    form.value.orderList = res.rows;

    loading.value = false;
  });
}

function getWorkOrderList(workOrderCode) {
  listWorkOrder({ workOrderCode }).then((res) => {
    // workOrderList.value = res.rows;
    workOrderList.value = res.rows.map((item) => {
      return {
        ...item,
        planTime: [item.planStartTime, item.planEndTime],
        // sectionList:
        //   workshopOptions.value.find((items) => {
        //     return items.code == items.lineCode;
        //   })?.children || [],
      };
    });
    form.value.remark = res.rows[0].remark;
    getMatCodeListData("edit");
  });
}
function getWorkSection(){
  depeIdSelectList({
      deptType: "line",
      deptCode: form.value.orderList[0].workSection,
    }).then((res) => {
      if(res&& res.data && res.data.length){
        res.data.forEach(element => {
          element.code=element.deptCode
          element.name=element.deptName
        });
      }
      workshopOptions.value = res.data;
    });
}
function handleBatchSettings() {
  if (form?.value?.orderList.length) {
    openWorderOrderBatch.value = true;
    getMatCodeListData("edit");
  } else {
    proxy.$modal.msgError("请先选择生产订单！");
  }
}

function getMatCodeListData(type) {
  let params = {
    matCode: form.value.orderList[0].prodCode,
    planNum: form.value.orderList[0].planNumber,
  };
  
  getMatCodeList(params).then((res) => {
    workshopOptions.value = res?.data || [];
    if (type == "edit") {
      console.log(
        workOrderList.value,
        "workOrderList.value",
        workshopOptions.value
      );
      workOrderList.value = workOrderList.value.map((item) => {
        return {
          ...item,
          sectionList:
            workshopOptions.value.find((items) => {
              return items.code == item.lineCode;
            })?.children || [],
        };
      });
    }
  });
}

function handleSearchProdChange(lineCode, index) {
  workOrderList.value[index].sectionCode = "";
  workOrderList.value[index].planNumber = "";
  workOrderList.value[index].sectionList =
    workshopOptions.value.find((item) => {
      return item.code == lineCode;
    })?.children || [];
  if(workOrderList.value[index].sectionList.length){

  } else{
    depeIdSelectList({
      deptType: "craft",
      deptCode: lineCode,
    }).then((res) => {
      if(res&& res.data && res.data.length){
        res.data.forEach(element => {
          element.code=element.deptCode
          element.name=element.deptName
        });
      }
      workOrderList.value[index].sectionList = res.data;
    });
  }
}

function handleSearchSectionChange(sectionCode, index) {
  workOrderList.value[index].planNumber =
    workOrderList.value[index].sectionList.find((item) => {
      return item.code == sectionCode;
    })?.number || 50;
}

function handleDel(row) {
  proxy.$modal
    .confirm("是否确认移除？")
    .then(function () {
      dsd(row);
    })
    .then(() => {
      proxy.$modal.msgSuccess("移除成功");
    })
    .catch(() => {});
}
function dsd(row) {
  let _list = workOrderList.value;
  for (let i in _list) {
    if (_list[i]?.idClone && _list[i].idClone == row.idClone) {
      _list.splice(i, 1);
    }
    if (_list[i]?.id && _list[i].id == row.id) {
      _list.splice(i, 1);
    }
  }
}

function handleAddWorkOrder() {
  if (form?.value?.orderList.length) {
    workOrderList.value.push({
      idClone: new Date().getTime(),
      orderCode: "",
      lineCode: "",
      sectionCode: "",
      planNumber: "",
      unit: form.value.orderList[0].unit,
      planStartTime: "",
      planEndTime: "",
    });
    getWorkSection()

  } else {
    proxy.$modal.msgError("请先选择生产订单！");
  }
}
function handleDisOrder() {
  if (form?.value?.orderList.length) {
    openDisOrder.value = true;
  } else {
    proxy.$modal.msgError("请先选择生产订单！");
  }
}

function changeList(val) {
  openOrder.value = false;
  if (val.length) {
    form.value.orderList = val;
    form.value.source = val[0].source;
    proxy.$refs["formRef"].validateField(["orderList"], async (valid) => {});
    getMatCodeListData();
  }
}

function changeWorderOrderBatchList(val) {
  openWorderOrderBatch.value = false;
  let _arr = workshopOptions.value;
  let _arrP = val.arrP;
  let _arrC = val.arrC;
  let _date = val.date;
  for (let i in _arrP) {
    for (let j in _arrC) {
      workOrderList.value.push({
        idClone: new Date().getTime(),
        orderCode: "",
        lineCode: _arrP[i],
        sectionCode: _arrC[i],
        planNumber: "",
        unit: form.value.orderList[0].unit,
        planStartTime: _date[0],
        planEndTime: _date[1],
        // sectionCode planTime
        planTime: [_date[0], _date[1]],
        sectionList:
          workshopOptions.value.find((item) => {
            return item.code == _arrP[i];
          })?.children || [],
      });
    }
  }
}

function changeDisOrderList() {
  openDisOrder.value = false;
}

function submitForm() {
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      if (workOrderList.value.length == 0) {
        return proxy.$modal.msgError("请先选择生产工单！");
      }
      for (let index = 0; index < workOrderList.value.length; index++) {
        const element = workOrderList.value[index];
        if (!element.workOrderCode) {
          return proxy.$modal.msgError(
            `生产工单 第${index + 1}行工单编号未填写`
          );
        }
        if (!element.lineCode) {
          return proxy.$modal.msgError(`生产工单 第${index + 1}行产线未选择`);
        }
        if (!element.sectionCode) {
          return proxy.$modal.msgError(`生产工单 第${index + 1}行工艺段未选择`);
        }
        if (element.planNumber === "" || element.planNumber === null) {
          return proxy.$modal.msgError(
            `生产工单 第${index + 1}行计划产量未填写`
          );
        }
        if (!element.planTime) {
          return proxy.$modal.msgError(
            `生产工单 第${index + 1}行计划时间未选择`
          );
        }
      }
      loading.value = true;
      console.log(form.value, workOrderList.value, "aaaaaaaaa");
      let newList = workOrderList.value.map((item) => {
        return {
          ...item,
          orderCode: form.value.orderList[0].orderCode,
          prodCode: form.value.orderList[0].prodCode,
          prodName: form.value.orderList[0].prodName,
          factory: form.value.orderList[0].factory,
          workSection: form.value.orderList[0].workSection,
          source: form.value?.source || form.value.orderList[0].source,
          remark: form.value?.remark || form.value.orderList[0].remark,
          planStartTime: item.planTime[0],
          planEndTime: item.planTime[1],
        };
      });
      if (form.value.id) {
        addWorkOrder(newList).then((res) => {
          proxy.$modal.msgSuccess("编辑成功");
          loading.value = false;
          cancel();
        }).catch((err) => {
          loading.value = false;
          });
      } else {
        addWorkOrder(newList).then((res) => {
          proxy.$modal.msgSuccess("提交成功");
          loading.value = false;
          cancel();
        }).catch((err) => {
          loading.value = false;
            console.log(err);
          });
      }
    }
  });
}
function cancel() {
  emit("close");
}
function handleOrderList() {
  openOrder.value = true;
}

/** 表单重置 */
function reset() {
  form.value = {
    name: undefined,
    type: undefined,
  };
  formRef.value.resetFields();
}
onMounted(async () => {
  const { data } = attrs;
  console.log(data, data?.order, "===================================");
  if (data?.order) {
    let order = JSON.parse(data.order);
    if (order?.id) {
      form.value.orderList = [JSON.parse(data?.order || "")];
      getMatCodeListData();
      actions.value = [
        {
          text: "取 消",
          theme: "",
          handle: () => {
            cancel();
          },
        },
        {
          text: "确 定",
          theme: "primary",
          handle: () => {
            submitForm();
          },
          loading: false,
        },
      ];
      emit("setActions", actions.value);
    }
  }

  if (data?.row?.id) {
    getDetail(data.row.orderCode);
    getWorkOrderList(data.row.workOrderCode);
    parentHandleType.value = data?.type;
    if (parentHandleType.value == "view") {
      actions.value = [
        {
          text: "取 消",
          theme: "",
          handle: () => {
            cancel();
          },
        },
      ];
      emit("setActions", actions.value);
    } else {
      actions.value = [
        {
          text: "取 消",
          theme: "",
          handle: () => {
            cancel();
          },
        },
        {
          text: "确 定",
          theme: "primary",
          handle: () => {
            submitForm();
          },
          loading: false,
        },
      ];
      emit("setActions", actions.value);
    }
  } else {
    actions.value = [
      {
        text: "取 消",
        theme: "",
        handle: () => {
          cancel();
        },
      },
      {
        text: "确 定",
        theme: "primary",
        handle: () => {
          submitForm();
        },
        loading: false,
      },
    ];
    emit("setActions", actions.value);
  }
});
</script>
<style lang="scss" scoped>
.wordOrderDiv {
  display: flex;
  justify-content: space-between;
}
:deep(.tableTrayQuality .el-form-item) {
  margin-bottom: 0 !important;
}
:deep(.el-table table tr th.start div:before) {
  content: "*";
  color: red;
}
:deep(.el-table table tr .noShowStar.start div:before) {
  content: "";
}

</style>
